define([
	'jquery',
	'jquery-validation',
	'jquery-extension',
	'layui',
	'bootstrap-datetimepicker',
	'bootstrap-datetimepicker-zh-CN',
	'bootstrap-table',
	'bootstrap-table-zh-CN',
	'bootstrap-table-mobile',
	'form-repeater',
], function() {
	return {
		initAddDialog: function(){
			// 表单验证
			$("#dict_add_form").validate({
				rules: {
					code: {
						required: true,
						rangelength:[2,10]
					},
					desc: {
						maxlength:10
					},
					sort: {
						required: true,
						number: true
					}
				},
				messages:{
					code: {
						required: "编码必填.",
						rangelength: $.validator.format("编码最小长度:{0}, 最大长度:{1}。")
					},
					desc: {
						maxlength: $.validator.format("描述最大长度:{0}。")
					},
					sort: {
						required: "排序必填.",
						number: "必须为数字"
					}
				},
			    errorPlacement: function(error,element) {
			    	$(element).parent().addClass('has-error');
			        $(element).after(error);
			    },
				success:function(element) {
			        $(element).parent().removeClass('has-error');
			        $(element).parent().find('label').remove();
			    },
			    // 是否在提交表单时验证
				onsubmit: false,
				// 是否在获取焦点时验证
				onfocusout:false,
				// 是否在敲击键盘时验证
				onkeyup:false,
				// 是否在点击时验证
				onclick: false,
				// 提交表单后，（第一个）未通过验证的表单获得焦点
				focusInvalid:true,
				// 当未通过验证的元素获得焦点时，移除错误提示
				focusCleanup:false,
			});
		},
		initUpdateDialog: function(){
			// 表单验证
			$("#dict_update_form").validate({
				rules: {
					code: {
						required: true,
						rangelength:[2,10]
					},
					desc: {
						maxlength:10
					},
					sort: {
						required: true,
						number: true
					}
				},
				messages:{
					code: {
						required: "编码必填.",
						rangelength: $.validator.format("编码最小长度:{0}, 最大长度:{1}。")
					},
					desc: {
						maxlength: $.validator.format("描述最大长度:{0}。")
					},
					sort: {
						required: "排序必填.",
						number: "必须为数字"
					}
				},
			    errorPlacement: function(error,element) {
			    	$(element).parent().addClass('has-error');
			        $(element).after(error);
			    },
				success:function(element) {
			        $(element).parent().removeClass('has-error');
			        $(element).parent().find('label').remove();
			    },
			    // 是否在提交表单时验证
				onsubmit: false,
				// 是否在获取焦点时验证
				onfocusout:false,
				// 是否在敲击键盘时验证
				onkeyup:false,
				// 是否在点击时验证
				onclick: false,
				// 提交表单后，（第一个）未通过验证的表单获得焦点
				focusInvalid:true,
				// 当未通过验证的元素获得焦点时，移除错误提示
				focusCleanup:false,
			});
		},
		initPage: function(){
			// 1 初始化日期控件
			$('#dict_start_date').datetimepicker({
				language: 'zh-CN',
				format: 'yyyy-mm-dd hh:ii:00',
				autoclose: true
			});
			
			$('#dict_end_date').datetimepicker({
				language: 'zh-CN',
				format: 'yyyy-mm-dd hh:ii:00',
				autoclose: true
			});
			
			// 2 初始化表单控件
			$('#dict_datatable').bootstrapTable({
				url : "/system/dict/query", 
				method : 'post', 
				toolbar : '#dict_toolbar',
				uniqueId: "id",
				striped: true,
				cache: false,
				pagination : true, 
				sortable: false,
				singleSelect : false,
				search: true,
				showColumns: true,
				showToggle:false,
				cardView: false,
				showRefresh: true,
				clickToSelect: true,
				minimumCountColumns: 5,
				queryParams : function(params) {
					return {
						limit : params.limit,
						offset : params.offset,
						keywords: params.search,
						sortName:'sort',
						code: $("#dict_content").find("form").find("input[name='code']").val(),
						desc: $("#dict_content").find("form").find("input[name='desc']").val(),
						delFlag: $("#dict_content").find("form").find("select option:selected").val(),
						startTime: $("#dict_content").find("form").find("input[name='startTime']").val(),
						endTime: $("#dict_content").find("form").find("input[name='endTime']").val()
					};
				},
				sidePagination : "server",
				pageNumber:1, 
				pageSize : 15,
				pageList: [15, 25, 50, 100],
				columns : [
					{
						checkbox : true
					},
					{
						field : 'id',
						title : '编号'
					},
					{
						field : 'code',
						title : '编码',
						formatter: function(value, row, index){
							return '<font color="red"> '+value+' </font>';
						}
					},
					{
						field : 'desc',
						title : '描述',
					},
					{
						field : 'values',
						title : '字典数据',
						width : '150px',
						align : 'left',
						formatter :function(value, row, index){
							if(!(value instanceof Array)){
								return value;
							}
							var arr = value;
							var result = '';
							for(var i=0; i<arr.length; i++){
								var code = arr[i].code;
								var desc = arr[i].desc;
								result = result + code+":"+desc+", ";
							}
							result = result.substring(0, result.lastIndexOf(', '));
							return result;
						}
					},
					{
						field : 'sort',
						title : '排序',
					},
					{
						visible : true,
						field : 'status',
						title : '状态',
						formatter: function(value, row, index){
							if(value==0){
								return '<span class="text-danger"><i class="fa fa-circle"></i> 禁用</span>';
							}else{
								return '<span class="text-success"><i class="fa fa-circle"></i> 启用</span>';
							}
						}
					},
					{
						visible : true,
						field : 'createTime',
						width : '150px',
						title : '创建时间'
					},
					{
						field : 'updateTime',
						width : '150px',
						title : '最后修改时间'
					},
					{
						title : '操作',
						field : '',
						align : 'center',
						formatter : function(value, row, index) {
							var b1 = '<a href="javascript:void(0);" class="btn btn-xs btn-success btn-editone" onclick="dict_update('+row['id']+')"><i class="fa fa-pencil"></i></a>';
							var b2 = '<a href="javascript:;" class="btn btn-xs btn-success btn-delone" onclick="dict_delete('+row['id']+')"><i class="fa fa-trash"></i></a>';
							return b1 + b2;
						}
					} 
				]
			});
			
			// 初始化手机响应式
			var docW = window.innerWidth;
			if (docW < 768) {
				$("#dict_search_plus").show();
				$("#dict_search_plus_btn").hide();
				$("#dict_content .bootstrap-table .fixed-table-toolbar input[type='text']").hide();
			}else{
				$("#dict_search_plus").hide();
			}
		}
	}
})

// 添加字典值
function add_dict_value(obj){
	$(obj).parent().parent().find(".form-repeater").append(
			'<div class="form-group value_code_desc">'+
			'	<input type="text" name="valueCode" class="form-control input-inline input-sm" placeholder="值">'+
			'	<input type="text" name="valueDesc" class="form-control input-inline input-sm" placeholder="描述">'+
			'	<button class="btn btn-success btn-sm" type="button" onclick="delete_dict_value(this)">'+
			'		<i aria-hidden="true" class="fa fa-trash"></i>'+
			'	</button>'+
	'</div>');
}

// 删除字典值
function delete_dict_value(obj){
	$(obj).parent().remove();
}

// 保存字典
function add_dict(){
	// Step1: 表单验证
	var valid = $("#dict_add_form").valid();
	var value_valid = true;
	$(".value_code_desc input").each(function(){
		if($(this).val()==''){
			$(this).addClass("error");
			value_valid = false;
		}else{
			$(this).removeClass("error");
		}
	});
	if(!valid || !value_valid){
		return;
	}
	
	// Step2: 获取输入数据，拼装成请求数据
	var code = $("input[name='code']").val();
	var desc = $("input[name='desc']").val();
	var sort = parseInt($("input[name='sort']").val());
	var status = $("input[name='status']:checked").val();
	var values = [];
	$(".form-repeater .value_code_desc").each(function(){
		var valueCode = $(this).find("input[name='valueCode']").val();
		var valueDesc = $(this).find("input[name='valueDesc']").val();
		values.push({code:valueCode,desc:valueDesc});
	});
	var data = {
		code:code,
		desc:desc,
		sort:sort,
		status:status,
		values:values
	};
	
	// Step3: 提交表单
    $.ajax({
    	url:"/system/dict/add",
        type:"post",
        dataType:'json',
        contentType:"application/json;charset=utf-8",
        data:JSON.stringify(data),
        async:false,
        success:function(data){
        	if(data.code!='10000'){
        		parent.layer.alert(data.msg, {icon: 2});
        		var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    			parent.layer.close(index);
        		return;
        	}
        	parent.layer.alert(data.msg, {icon: 1});
        	//$('#dict_datatable', window.parent.document).bootstrapTable('refresh', null);
        	var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
			parent.layer.close(index);
        	parent.dict_reload();
        },
        error: function (response, ajaxOptions, thrownError) {
        	errorCallBack(response, ajaxOptions, thrownError);                
        }
    });
}

// 保存字典
function update_dict(){
	// Step1: 表单验证
	var valid = $("#dict_update_form").valid();
	var value_valid = true;
	$(".value_code_desc input").each(function(){
		if($(this).val()==''){
			$(this).addClass("error");
			value_valid = false;
		}else{
			$(this).removeClass("error");
		}
	});
	if(!valid || !value_valid){
		return;
	}
	
	// Step2: 获取输入数据，拼装成请求数据
	var id = $("input[name='id']").val();
	var code = $("input[name='code']").val();
	var desc = $("input[name='desc']").val();
	var sort = parseInt($("input[name='sort']").val());
	var status = $("input[name='status']:checked").val();
	var values = [];
	$(".form-repeater .value_code_desc").each(function(){
		var valueCode = $(this).find("input[name='valueCode']").val();
		var valueDesc = $(this).find("input[name='valueDesc']").val();
		values.push({code:valueCode,desc:valueDesc});
	});
	var data = {
		id: id,
		code:code,
		desc:desc,
		sort:sort,
		status:status,
		values:values
	};
	
	// Step3: 提交表单
    $.ajax({
    	url:"/system/dict/update",
        type:"post",
        dataType:'json',
        contentType:"application/json;charset=utf-8",
        data:JSON.stringify(data),
        async:false,
        success:function(data){
        	if(data.code!='10000'){
        		parent.layer.alert(data.msg, {icon: 2});
        		var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    			parent.layer.close(index);
        		return;
        	}
        	parent.layer.alert(data.msg, {icon: 1});
        	parent.dict_reload();
        	var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
			parent.layer.close(index);
        },
        error: function (response, ajaxOptions, thrownError) {
        	errorCallBack(response, ajaxOptions, thrownError);                
        }
    });
}

//添加字典
function dict_add() {
	var docW = window.innerWidth;
	var area = [ '100%', '100%' ];
	var maxmin = false;
	if (docW >= 768) {
		area = [ '720px', '500px' ];
		maxmin = true;
	}
	var i = layer.open({
		type : 2,
		title : '添加字典',
		maxmin : maxmin,
		shadeClose : false,
		area : area,
		content : '/system/dict/add',
		btn : [ '保存+btn-success+fa-check', '取消+btn-success+fa-close' ],
		btn1 : function(index) {
			var loadindex = layer.load(1, {time: 5*1000});	
			$("#layui-layer-iframe" + i)[0].contentWindow.add_dict();
			layer.close(loadindex);
		},
		btn2 : function(index) {
			layer.close(i);
		}
	});
	if (docW >= 768) {
		layer.restore(i);
	}else{
		layer.full(i);
	}
}

//删除字典
function dict_delete(id){
	layer.confirm('确定要删除吗？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$.ajax({
			url : '/system/dict/delete',
			type : "post",
			data : {'id' : id},
			success : function(data) {
				if (data.code != '10000') {
					layer.alert(data.msg,{icon: 2});
					return;
				}
				layer.alert(data.msg, {icon: 1});
				dict_reload();
			},
	        error: function (response, ajaxOptions, thrownError) {
	        	errorCallBack(response, ajaxOptions, thrownError);                
	        }
		});
	})
}

// 批量删除
function dict_batch_delete(){
	var rows = $('#dict_datatable').bootstrapTable('getSelections'); 
	if (rows.length == 0) {
		layer.alert("请至少选择一条记录!",{icon: 7});
		return;
	}
	layer.confirm("确定要删除选中的'" + rows.length + "'条记录吗?", {
		btn : [ '确定', '取消' ]
	}, function() {
		var ids = [];
		$.each(rows, function(i, row) {
			ids.push(row['id']);
		});
		$.ajax({
			type : 'post',
			data : {ids:ids},
			dataType : 'json',
			url : '/system/dict/batch_delete',
			success : function(data) {
				if (data.code != '10000') {
					layer.alert(data.msg,{icon: 2});
					return;
				}
				layer.alert(data.msg, {icon: 1});
				dict_reload();
			},
	        error: function (response, ajaxOptions, thrownError) {
	        	errorCallBack(response, ajaxOptions, thrownError);                
	        }
		});
	}, function() {});
}

// 显示高级搜索
function dict_search_plus(){
	var search = $('#dict_datatable').parents('.bootstrap-table').find('.fixed-table-toolbar').find("input[type='text']");
	if(!$(search).is(":hidden")){
		// 隐藏普通搜索
		$(search).val('').hide();
		// 显示高级搜索
		$("#dict_search_plus").show();
	}else{
		$("#dict_search_plus").find("form")[0].reset();
		$("#dict_search_plus").hide();
		$(search).show();
	}
}

//高级查询
function dict_search_submit(){
	$('#dict_datatable').bootstrapTable('refresh', null);
}

// 修改字典
function dict_update(id){
	var docW = window.innerWidth;
	var area = [ '100%', '100%' ];
	var maxmin = false;
	if (docW >= 768) {
		area = [ '720px', '500px' ];
		maxmin = true;
	}
	var i = layer.open({
		type : 2,
		title : '修改字典',
		maxmin : maxmin,
		shadeClose : false,
		area : area,
		content : '/system/dict/update?id='+id,
		btn : [ '保存+btn-success+fa-check', '取消+btn-success+fa-close' ],
		btn1 : function(index) {
			var loadindex = layer.load(1, {time: 5*1000});	
			$("#layui-layer-iframe" + i)[0].contentWindow.update_dict();
			layer.close(loadindex);
		},
		btn2 : function(index) {
			layer.close(i);
		}
	});
	if (docW >= 768) {
		layer.restore(i);
	}else{
		layer.full(i);
	}
}

// 重新加载datatable
function dict_reload(){
	$('#dict_datatable').bootstrapTable('refresh', null);
}